package com.cheems.cheems_spring_ai.config;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

@Slf4j
@Component
public class Tools {

    @Tool(description = "我要咨询")
    String search(@ToolParam(description = "咨询内容") String
                messaage) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        URI uri = URI.create("https://api.dify.ai/v1/chat-messages");
        log.info("messaage,{}", messaage);
        // 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("inputs", new JSONObject());
        requestBody.put("query", messaage);
        requestBody.put("response_mode", "blocking");
        requestBody.put("conversation_id", "");
        requestBody.put("user", "jtb");
        requestBody.put("files", new String[]{});

        try {
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            log.info("本地主机地址: {}", hostAddress);
            
            log.info("请求体JSON: {}", requestBody.toJSONString());
            
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(uri)
                    .header("Authorization", "Bearer app-oK7lNjDsdQ15YEIZ86gGPu18")
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody.toJSONString()))
                    .build();
                
            log.info("HTTP请求已构建");
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            log.info("响应状态码: {}", response.statusCode());
            log.info("响应体: {}", response.body());

            // 从响应中提取核心回答（answer字段）
            String responseBody = response.body();
            JSONObject jsonResponse = JSONObject.parseObject(responseBody);
            String answer = jsonResponse.getString("answer");
            
            // 提取出处信息
            StringBuilder sources = new StringBuilder();
            if (jsonResponse.containsKey("metadata") && jsonResponse.getJSONObject("metadata").containsKey("retriever_resources")) {
                JSONObject metadata = jsonResponse.getJSONObject("metadata");
                Object retrieverResources = metadata.get("retriever_resources");
                if (retrieverResources instanceof Iterable) {
                    for (Object resource : (Iterable<?>) retrieverResources) {
                        if (resource instanceof JSONObject) {
                            JSONObject resourceJson = (JSONObject) resource;
                            if (resourceJson.containsKey("content")) {
                                sources.append("出处: ").append(resourceJson.getString("content")).append("\n\n");
                            }
                        }
                    }
                }
            }
            
            log.info("核心回答: {}", answer);
            log.info("出处信息大小: {}", sources.length());
            
            // 组合回答和出处信息
            String result = answer;
            if (sources.length() > 0) {
                result += "\n\n参考资料:\n" + sources;
            }
            
            return result;
        } catch (Exception e) {
            log.error("执行咨询工具时发生错误: ", e);
            return "执行过程中出现错误: " + e.getMessage();
        }
    }

    @Tool(description = "查询农大相关信息")
    String retrieveFromDataset(@ToolParam(description = "咨询内容") String message) throws IOException, InterruptedException {
        
        HttpClient client = HttpClient.newHttpClient();
        URI uri = URI.create("https://api.dify.ai/v1/datasets/69f4473f-1ac5-483e-9906-be1f61dcc79b/retrieve");
        log.info("检索内容: {}", message);
        
        // 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("query", message);
        
        // 构建retrieval_model对象
        JSONObject retrievalModel = new JSONObject();
        retrievalModel.put("search_method", "keyword_search");
        retrievalModel.put("reranking_enable", false);
        retrievalModel.put("reranking_mode", "");
        
        JSONObject rerankingModel = new JSONObject();
        rerankingModel.put("reranking_provider_name", "");
        rerankingModel.put("reranking_model_name", "");
        retrievalModel.put("reranking_model", rerankingModel);
        
        retrievalModel.put("weights", "");
        retrievalModel.put("top_k", 1);
        retrievalModel.put("score_threshold_enabled", false);
        retrievalModel.put("score_threshold", "");
        
        requestBody.put("retrieval_model", retrievalModel);
        
        try {
            log.info("请求体JSON: {}", requestBody.toJSONString());
            
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(uri)
                    .header("Authorization", "Bearer dataset-80CNBDP8vdorljcHM7oAbSk9")
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody.toJSONString()))
                    .build();
                
            log.info("HTTP请求已构建");
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            log.info("响应状态码: {}", response.statusCode());
            log.info("响应体: {}", response.body());

            // 解析响应
            String responseBody = response.body();
            JSONObject jsonResponse = JSONObject.parseObject(responseBody);
            
            StringBuilder result = new StringBuilder("查询结果：\n\n");
            
            // 添加查询内容
            if (jsonResponse.containsKey("query") && jsonResponse.getJSONObject("query").containsKey("content")) {
                result.append("您的问题: ").append(jsonResponse.getJSONObject("query").getString("content")).append("\n\n");
            }
            
            // 提取记录内容
            if (jsonResponse.containsKey("records") && !jsonResponse.getJSONArray("records").isEmpty()) {
                for (int i = 0; i < jsonResponse.getJSONArray("records").size(); i++) {
                    JSONObject record = jsonResponse.getJSONArray("records").getJSONObject(i);
                    if (record.containsKey("segment") && record.getJSONObject("segment").containsKey("content")) {
                        JSONObject segment = record.getJSONObject("segment");
                        result.append("找到以下信息：\n")
                              .append(segment.getString("content"))
                              .append("\n\n");
                        
                        // 添加文档信息
                        if (segment.containsKey("document") && segment.getJSONObject("document").containsKey("name")) {
                            result.append("来源文档: ").append(segment.getJSONObject("document").getString("name"));
                        }
                    }
                }
            } else {
                result.append("未找到相关信息。");
            }
            
            return result.toString();
        } catch (Exception e) {
            log.error("执行检索工具时发生错误: ", e);
            return "检索过程中出现错误: " + e.getMessage();
        }
    }

    @Tool(description = "我要请假")
    void leave(@ToolParam(description = "请假原因") String reason , @ToolParam(description = "请假时间") String time, @ToolParam(description = "请假地点") String place , @ToolParam(description = "请假人") String name) {
        System.out.println(reason+" "+time+" "+place+""+name);
    }

    @Tool(description = "申请教室")
    void applyForClass(@ToolParam(description = "申请原因") String reason , @ToolParam(description = "申请时间") String time, @ToolParam(description = "申请地点") String place , @ToolParam(description = "申请人") String name) {
        System.out.println(reason+" "+time+" "+place+""+name);
    }

}
